<template>
  <div class="record-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2 class="page-title">
        <i class="el-icon-document"></i>
        预约记录
      </h2>
      <p class="page-subtitle">查看您的心理咨询预约历史记录</p>
    </div>

    <!-- 筛选区域 -->
    <div class="filter-container">
      <div class="section-header">
        <i class="el-icon-search"></i>
        <span>筛选条件</span>
      </div>
      <el-form :inline="true" :model="queryParams" class="filter-form">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="预约状态">
              <el-select
                v-model="queryParams.status"
                placeholder="请选择状态"
                style="width: 100%"
                clearable
                @change="handleQuery"
              >
                <el-option label="全部" value=""></el-option>
                <el-option label="待确认" value="pending"></el-option>
                <el-option label="已确认" value="confirmed"></el-option>
                <el-option label="进行中" value="ongoing"></el-option>
                <el-option label="已完成" value="completed"></el-option>
                <el-option label="已取消" value="cancelled"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="6">
            <el-form-item label="咨询方式">
              <el-select
                v-model="queryParams.consultationType"
                placeholder="请选择咨询方式"
                style="width: 100%"
                clearable
                @change="handleQuery"
              >
                <el-option label="全部" value=""></el-option>
                <el-option label="电话咨询" value="phone"></el-option>
                <el-option label="视频咨询" value="video"></el-option>
                <el-option label="面对面咨询" value="offline"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="预约时间">
              <el-date-picker
                v-model="dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                style="width: 100%"
                value-format="yyyy-MM-dd"
                @change="handleQuery"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          
          <el-col :span="4">
            <el-form-item>
              <el-button type="primary" @click="handleQuery">查询</el-button>
              <el-button @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-container">
      <div class="stat-card">
        <div class="stat-icon pending">
          <i class="el-icon-time"></i>
        </div>
        <div class="stat-content">
          <h3>{{ statistics.pending }}</h3>
          <p>待确认</p>
        </div>
      </div>
      
      <div class="stat-card">
        <div class="stat-icon confirmed">
          <i class="el-icon-check"></i>
        </div>
        <div class="stat-content">
          <h3>{{ statistics.confirmed }}</h3>
          <p>已确认</p>
        </div>
      </div>
      
      <div class="stat-card">
        <div class="stat-icon completed">
          <i class="el-icon-circle-check"></i>
        </div>
        <div class="stat-content">
          <h3>{{ statistics.completed }}</h3>
          <p>已完成</p>
        </div>
      </div>
      
      <div class="stat-card">
        <div class="stat-icon total">
          <i class="el-icon-data-line"></i>
        </div>
        <div class="stat-content">
          <h3>{{ statistics.total }}</h3>
          <p>总计</p>
        </div>
      </div>
    </div>

    <!-- 预约记录列表 -->
    <div class="records-container">
      <div class="section-header">
        <i class="el-icon-tickets"></i>
        <span>预约记录</span>
        <div class="header-actions">
          <el-button type="text" @click="refreshData">
            <i class="el-icon-refresh"></i>
            刷新
          </el-button>
        </div>
      </div>

      <div v-loading="loading" class="records-list">
        <div 
          v-for="record in filteredRecords" 
          :key="record.id"
          class="record-card"
          :class="getRecordCardClass(record.status)"
        >
          <!-- 记录头部 -->
          <div class="record-header">
            <div class="record-info">
              <h3 class="appointment-title">
                <i class="el-icon-user"></i>
                {{ record.teacherName }}老师
              </h3>
              <div class="appointment-meta">
                <span class="appointment-id">预约编号：{{ record.appointmentId }}</span>
                <span class="appointment-time">{{ record.appointmentDate }} {{ record.timeSlot }}</span>
              </div>
            </div>
            <div class="record-status">
              <el-tag :type="getStatusTagType(record.status)" size="medium">
                {{ getStatusText(record.status) }}
              </el-tag>
            </div>
          </div>

          <!-- 记录内容 -->
          <div class="record-content">
            <div class="record-details">
              <div class="detail-item">
                <span class="detail-label">咨询方式：</span>
                <span class="detail-value">
                  <i :class="getConsultationIcon(record.consultationType)"></i>
                  {{ record.consultationMethod }}
                </span>
              </div>
              
              <div class="detail-item">
                <span class="detail-label">咨询费用：</span>
                <span class="detail-value price">¥{{ record.price }}</span>
              </div>
              
              <div class="detail-item" v-if="record.duration">
                <span class="detail-label">咨询时长：</span>
                <span class="detail-value">{{ record.duration }}分钟</span>
              </div>
              
              <div class="detail-item full-width" v-if="record.problemDescription">
                <span class="detail-label">咨询问题：</span>
                <span class="detail-value">{{ record.problemDescription }}</span>
              </div>
            </div>
          </div>

          <!-- 记录操作 -->
          <div class="record-actions">
            <el-button 
              v-if="record.status === 'pending'" 
              type="danger" 
              size="small" 
              plain
              @click="cancelAppointment(record)"
            >
              取消预约
            </el-button>
            
            <el-button 
              v-if="record.status === 'confirmed'" 
              type="warning" 
              size="small" 
              plain
              @click="rescheduleAppointment(record)"
            >
              改期
            </el-button>
            
            <el-button 
              v-if="record.status === 'completed'" 
              type="primary" 
              size="small" 
              plain
              @click="viewFeedback(record)"
            >
              查看反馈
            </el-button>
            
            <el-button 
              type="info" 
              size="small" 
              plain
              @click="viewDetails(record)"
            >
              详情
            </el-button>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-if="!loading && filteredRecords.length === 0" class="empty-state">
        <i class="el-icon-document-delete"></i>
        <h3>暂无预约记录</h3>
        <p>您还没有任何预约记录，快去预约心理咨询吧！</p>
        <el-button type="primary" @click="goToBooking">立即预约</el-button>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'RecordIndex',
  data() {
    return {
      loading: false,
      
      // 查询参数
      queryParams: {
        status: '',
        consultationType: '',
        pageNum: 1,
        pageSize: 10
      },
      
      // 日期范围
      dateRange: [],
      
      // 统计数据
      statistics: {
        pending: 0,
        confirmed: 0,
        completed: 0,
        total: 0
      },
      
      // 预约记录列表
      records: [],
      total: 0
    }
  },
  
  computed: {
    // 过滤后的记录
    filteredRecords() {
      let filtered = [...this.records]
      
      // 状态筛选
      if (this.queryParams.status) {
        filtered = filtered.filter(record => record.status === this.queryParams.status)
      }
      
      // 咨询方式筛选
      if (this.queryParams.consultationType) {
        filtered = filtered.filter(record => record.consultationType === this.queryParams.consultationType)
      }
      
      // 日期范围筛选
      if (this.dateRange && this.dateRange.length === 2) {
        const [startDate, endDate] = this.dateRange
        filtered = filtered.filter(record => {
          return record.appointmentDate >= startDate && record.appointmentDate <= endDate
        })
      }
      
      return filtered
    }
  },
  
  async mounted() {
    console.log('预约记录页面初始化中...')
    await this.loadData()
    console.log('预约记录页面初始化完成！')
  },
  
  methods: {
    // 加载数据
    async loadData() {
      this.loading = true
      try {
        await Promise.all([
          this.loadRecords(),
          this.loadStatistics()
        ])
      } catch (error) {
        console.error('加载数据失败:', error)
        this.$message.error('加载数据失败，请重试')
      } finally {
        this.loading = false
      }
    },
    
    // 加载预约记录
    async loadRecords() {
      try {
        // 模拟API调用延迟
        await new Promise(resolve => setTimeout(resolve, 800))
        
        // 生成模拟数据
        this.records = this.generateMockRecords()
        this.total = this.records.length
        
        console.log('加载了', this.records.length, '条预约记录')
      } catch (error) {
        console.error('获取预约记录失败:', error)
        this.$message.error('获取预约记录失败')
      }
    },
    
    // 加载统计数据
    async loadStatistics() {
      try {
        // 根据记录计算统计
        const stats = {
          pending: 0,
          confirmed: 0,
          completed: 0,
          total: 0
        }
        
        this.records.forEach(record => {
          stats.total++
          if (record.status === 'pending') stats.pending++
          else if (record.status === 'confirmed') stats.confirmed++
          else if (record.status === 'completed') stats.completed++
        })
        
        this.statistics = stats
        console.log('统计数据:', this.statistics)
      } catch (error) {
        console.error('获取统计数据失败:', error)
      }
    },
    
    // 生成模拟记录数据
    generateMockRecords() {
      const mockRecords = []
      const teachers = ['张心怡教授', '李明华老师', '王雅琴老师', '陈建国老师']
      const consultationMethods = [
        { type: 'phone', name: '电话咨询', price: 150 },
        { type: 'video', name: '视频咨询', price: 200 },
        { type: 'offline', name: '面对面咨询', price: 300 }
      ]
      const statuses = ['pending', 'confirmed', 'ongoing', 'completed', 'cancelled']
      const problems = [
        '学习压力过大，经常焦虑失眠',
        '人际关系处理困难，社交恐惧',
        '情绪波动较大，容易抑郁',
        '职业规划迷茫，对未来感到不安',
        '家庭关系紧张，亲子沟通困难',
        '恋爱关系困扰，情感问题',
        '自信心不足，自我认知偏差',
        '适应新环境困难，压力管理'
      ]
      
      // 生成20条记录
      for (let i = 1; i <= 20; i++) {
        const teacher = teachers[Math.floor(Math.random() * teachers.length)]
        const consultation = consultationMethods[Math.floor(Math.random() * consultationMethods.length)]
        const status = statuses[Math.floor(Math.random() * statuses.length)]
        const problem = problems[Math.floor(Math.random() * problems.length)]
        
        // 生成过去30天内的随机日期
        const date = new Date()
        date.setDate(date.getDate() - Math.floor(Math.random() * 30))
        const appointmentDate = date.toISOString().split('T')[0]
        
        // 随机时间段
        const hours = ['09:00-10:00', '10:30-11:30', '14:00-15:00', '15:30-16:30', '19:00-20:00']
        const timeSlot = hours[Math.floor(Math.random() * hours.length)]
        
        mockRecords.push({
          id: i,
          appointmentId: `AP${String(Date.now() + i).slice(-8)}`,
          teacherName: teacher.replace('老师', '').replace('教授', ''),
          teacherTitle: teacher.includes('教授') ? '主任医师、心理学博士' : '心理咨询师',
          appointmentDate,
          timeSlot,
          consultationType: consultation.type,
          consultationMethod: consultation.name,
          price: consultation.price,
          duration: status === 'completed' ? (45 + Math.floor(Math.random() * 15)) : null,
          problemDescription: problem,
          status,
          createdAt: new Date(date.getTime() - Math.random() * 7 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
          feedback: status === 'completed' ? '咨询效果很好，老师很专业，对我帮助很大。' : null
        })
      }
      
      // 按预约日期倒序排列
      return mockRecords.sort((a, b) => new Date(b.appointmentDate) - new Date(a.appointmentDate))
    },
    
    // 获取状态标签类型
    getStatusTagType(status) {
      const typeMap = {
        'pending': 'warning',
        'confirmed': 'primary',
        'ongoing': 'success',
        'completed': 'success',
        'cancelled': 'danger'
      }
      return typeMap[status] || 'info'
    },
    
    // 获取状态文本
    getStatusText(status) {
      const textMap = {
        'pending': '待确认',
        'confirmed': '已确认',
        'ongoing': '进行中',
        'completed': '已完成',
        'cancelled': '已取消'
      }
      return textMap[status] || '未知'
    },
    
    // 获取咨询方式图标
    getConsultationIcon(type) {
      const iconMap = {
        'phone': 'el-icon-phone',
        'video': 'el-icon-video-camera',
        'offline': 'el-icon-user-solid'
      }
      return iconMap[type] || 'el-icon-service'
    },
    
    // 获取记录卡片样式类
    getRecordCardClass(status) {
      return `status-${status}`
    },
    
    // 查询
    handleQuery() {
      console.log('执行查询:', this.queryParams, this.dateRange)
      this.loadStatistics() // 重新计算统计数据
    },
    
    // 重置查询
    resetQuery() {
      this.queryParams = {
        status: '',
        consultationType: '',
        pageNum: 1,
        pageSize: 10
      }
      this.dateRange = []
      this.handleQuery()
    },
    
    // 刷新数据
    async refreshData() {
      this.$message.info('正在刷新数据...')
      await this.loadData()
      this.$message.success('数据刷新成功')
    },
    
    // 取消预约
    cancelAppointment(record) {
      this.$confirm(`确定要取消与${record.teacherName}老师的预约吗？`, '取消预约', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 模拟取消操作
        record.status = 'cancelled'
        this.loadStatistics()
        this.$message.success('预约已取消')
      }).catch(() => {
        this.$message.info('已取消操作')
      })
    },
    
    // 改期预约
    rescheduleAppointment(record) {
      this.$message.info('改期功能开发中，请联系客服处理')
    },
    
    // 查看反馈
    viewFeedback(record) {
      this.$alert(record.feedback || '暂无反馈信息', '咨询反馈', {
        confirmButtonText: '确定',
        type: 'success'
      })
    },
    
    // 查看详情
    viewDetails(record) {
      const details = `预约编号：${record.appointmentId}\n咨询老师：${record.teacherName}\n预约时间：${record.appointmentDate} ${record.timeSlot}\n咨询方式：${record.consultationMethod}\n咨询费用：¥${record.price}\n${record.duration ? `咨询时长：${record.duration}分钟\n` : ''}咨询问题：${record.problemDescription}\n预约状态：${this.getStatusText(record.status)}\n创建时间：${record.createdAt}`
      
      this.$alert(details, '预约详情', {
        confirmButtonText: '确定',
        type: 'info'
      })
    },
    
    // 跳转到预约页面
    goToBooking() {
      this.$router.push('/information/calendar')
    }
  }
}
</script>

<style scoped>
.record-container {
  padding: 24px;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  min-height: calc(100vh - 84px);
}

/* 页面头部 */
.page-header {
  margin-bottom: 24px;
  text-align: center;
}

.page-title {
  font-size: 28px;
  font-weight: 700;
  color: #2c3e50;
  margin: 0 0 8px 0;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.page-title i {
  margin-right: 12px;
  color: #409EFF;
}

.page-subtitle {
  font-size: 16px;
  color: #606266;
  margin: 0;
}

/* 筛选区域 */
.filter-container {
  background: linear-gradient(145deg, #ffffff 0%, #f8fafc 100%);
  padding: 24px;
  margin-bottom: 20px;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  backdrop-filter: blur(10px);
}

.section-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 2px solid #e2e8f0;
  position: relative;
}

.section-header i {
  font-size: 18px;
  color: #409EFF;
  margin-right: 8px;
}

.section-header span {
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
  letter-spacing: 0.5px;
}

.header-actions {
  margin-left: auto;
  display: flex;
  align-items: center;
}

.section-header::after {
  content: '';
  position: absolute;
  bottom: -2px;
  left: 0;
  width: 60px;
  height: 2px;
  background: linear-gradient(90deg, #409EFF, #67C23A);
  border-radius: 1px;
}

/* 统计卡片 */
.stats-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 24px;
}

.stat-card {
  background: linear-gradient(145deg, #ffffff 0%, #f8fafc 100%);
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  display: flex;
  align-items: center;
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.15);
}

.stat-icon {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  font-size: 24px;
  color: white;
}

.stat-icon.pending {
  background: linear-gradient(45deg, #e6a23c, #f7ba2a);
}

.stat-icon.confirmed {
  background: linear-gradient(45deg, #409EFF, #36a3f7);
}

.stat-icon.completed {
  background: linear-gradient(45deg, #67c23a, #85ce61);
}

.stat-icon.total {
  background: linear-gradient(45deg, #909399, #b1b3b8);
}

.stat-content h3 {
  font-size: 24px;
  font-weight: 700;
  color: #2c3e50;
  margin: 0 0 4px 0;
}

.stat-content p {
  font-size: 14px;
  color: #606266;
  margin: 0;
}

/* 记录容器 */
.records-container {
  background: linear-gradient(145deg, #ffffff 0%, #f8fafc 100%);
  padding: 24px;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  margin-bottom: 24px;
}

/* 记录列表 */
.records-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.record-card {
  background: white;
  border-radius: 12px;
  border: 2px solid #e4e7ed;
  padding: 20px;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.record-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 4px;
  height: 100%;
  background: #e4e7ed;
  transition: all 0.3s ease;
}

.record-card.status-pending::before {
  background: #e6a23c;
}

.record-card.status-confirmed::before {
  background: #409EFF;
}

.record-card.status-ongoing::before {
  background: #67c23a;
}

.record-card.status-completed::before {
  background: #67c23a;
}

.record-card.status-cancelled::before {
  background: #f56c6c;
}

.record-card:hover {
  border-color: #409EFF;
  box-shadow: 0 4px 16px rgba(64, 158, 255, 0.2);
  transform: translateY(-2px);
}

/* 记录头部 */
.record-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
}

.appointment-title {
  font-size: 18px;
  font-weight: 600;
  color: #2c3e50;
  margin: 0 0 8px 0;
}

.appointment-title i {
  margin-right: 8px;
  color: #409EFF;
}

.appointment-meta {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.appointment-id,
.appointment-time {
  font-size: 13px;
  color: #909399;
}

.appointment-time {
  font-weight: 600;
  color: #606266;
}

/* 记录内容 */
.record-content {
  margin-bottom: 16px;
}

.record-details {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 12px;
}

.detail-item {
  display: flex;
  align-items: center;
}

.detail-item.full-width {
  grid-column: 1 / -1;
  align-items: flex-start;
}

.detail-label {
  font-size: 14px;
  color: #606266;
  margin-right: 8px;
  min-width: 80px;
}

.detail-value {
  font-size: 14px;
  color: #2c3e50;
  flex: 1;
}

.detail-value.price {
  font-weight: 600;
  color: #e6a23c;
}

.detail-value i {
  margin-right: 4px;
  color: #409EFF;
}

/* 记录操作 */
.record-actions {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: #909399;
}

.empty-state i {
  font-size: 64px;
  color: #d3d4d6;
  margin-bottom: 16px;
}

.empty-state h3 {
  font-size: 18px;
  color: #606266;
  margin: 0 0 8px 0;
}

.empty-state p {
  font-size: 14px;
  margin: 0 0 24px 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .record-container {
    padding: 16px;
  }
  
  .stats-container {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .record-header {
    flex-direction: column;
    gap: 12px;
  }
  
  .record-details {
    grid-template-columns: 1fr;
  }
  
  .record-actions {
    justify-content: center;
  }
}

@media (max-width: 480px) {
  .stats-container {
    grid-template-columns: 1fr;
  }
  
  .stat-card {
    padding: 16px;
  }
  
  .page-title {
    font-size: 24px;
  }
}
</style>